/*
 * Copyright 2010 Aekold Helbrass
 *
 * This file is part of RosterComposer.
 *
 * RosterComposer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * RosterComposer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with RosterComposer.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.heresylabs.rostercomposer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;

/**
 *
 * @author Aekold Helbrass <Helbrass@gmail.com>
 */
public class TotalPointsComponent extends JButton implements ActionListener {

    private int cost;

    private int target;

    public TotalPointsComponent() {
        super.addActionListener(this);
        fireCostChanged();
    }

    private void fireCostChanged() {
        if (target < 1) {
            super.setText("<html><div style=\"font-size:120%\"><b>" + cost);
            return;
        }

        StringBuilder sb = new StringBuilder();
        sb.append("<html><table border=\"0\" cellspacing=\"0\" cellpadding=\"1\"><tr><td style=\"font-size:120%;font-weight:bold\">");
        sb.append(cost).append('/').append(target);
        sb.append("</td></tr><tr><td align=\"right\"");
        int diff = target - cost;
        if (diff < 0) {
            sb.append(" style=\"color:red\">");
            sb.append(-diff).append(" pts exceed");
        }
        else {
            sb.append('>');
            sb.append(diff).append(" pts left");
        }
        sb.append("</td></tr></table>");

        String val = sb.toString();

        super.setText(val);
        super.setToolTipText(val);
    }

    public int getCost() {
        return cost;
    }

    public void setCost(int cost) {
        this.cost = cost;
        fireCostChanged();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String s = JOptionPane.showInputDialog(this, "Target roster points:", String.valueOf(target));
        try {
            int res = Integer.parseInt(s);
            if (res < 0) {
                return;
            }
            target = res;
            fireCostChanged();
        }
        catch (Exception ignore) {
            // if we got exception - something went wrong, but we should not care too much
        }
    }

}
